package com.school.edupoint.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.school.edupoint.config.EduContext;
import com.school.edupoint.mapper.GiftMapper;
import com.school.edupoint.mapper.StudentActivityHistoryMapper;
import com.school.edupoint.model.Activity;
import com.school.edupoint.model.Gift;
import com.school.edupoint.template.OssTemplate;
import com.school.edupoint.vo.GiftVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class GiftService {
    @Autowired
    private EduContext eduContext;
    @Autowired
    private GiftMapper giftMapper;
    @Autowired
    private OssTemplate ossTemplate;
    @Autowired
    private StudentActivityHistoryMapper studentActivityHistoryMapper;

    /**
     * 分页、模糊查询
     * @param title
     * @param pageNum
     * @param pageSize
     * @return
     */
    public IPage<Gift> selectPage(String title, int pageNum, int pageSize) {
        // 创建分页对象
        Page<Gift> page = new Page<>(pageNum, pageSize);
        // 构建查询条件
        LambdaQueryWrapper<Gift> wrapper = new LambdaQueryWrapper<>();
        // 如果 title 有值，则加上模糊查询条件
        if (title != null && !title.isEmpty()) {
            wrapper.like(Gift::getName, title);
        }
        // 统一按创建时间降序排序
        wrapper.orderByDesc(Gift::getCreateTime);

        return giftMapper.selectPage(page, wrapper);
    }

    /**
     * 查询活动详情
     * @param giftId
     * @return
     */
    public Gift getInfo(Long giftId) {
        LambdaQueryWrapper<Gift> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Gift::getId, giftId);
        return giftMapper.selectOne(queryWrapper);
    }

    /**
     * 新增礼物
     * @param giftVO
     * @return
     */
    public GiftVO save(GiftVO giftVO) {
//        新增，反之更新
        if (giftVO.getId() == null) {
            System.out.println("eduContext.getUser()数据为："+eduContext.getUser().getId());
            giftVO.setCreateBy(eduContext.getUser().getId());
            giftVO.setCreateTime(new Date());
            giftVO.setReg(0);
            giftMapper.insert(giftVO);
        } else {
            String oldPoster = giftVO.getOldPoster();
            if (oldPoster != null && !oldPoster.isEmpty()) {
                ossTemplate.asyncDeleteByUrl(oldPoster); // 异步删除
            }

            giftVO.setUpdateBy(eduContext.getUser().getId());
            giftVO.setUpdateTime(new Date());
            giftMapper.updateById(giftVO);
        }
        return giftVO;
    }

    /**
     * 上传图片
     * @param photo
     * @return
     */
    public String uploadPhoto(MultipartFile photo) throws Exception {
        //将图片上传到阿里云Oss

        String photoUrl = ossTemplate.upload(photo.getOriginalFilename(), photo.getInputStream());

        return photoUrl;
    }

    /**
     * 根据礼物ID删除礼物
     * @param id
     */
    public void delete(Integer id) {
        giftMapper.deleteById(id);
    }

    public String selectMaxGiftTitle() {

        return giftMapper.selectMaxGiftTitle();
    }

    public String selectMaxGiftImg() {

        return giftMapper.selectMaxGiftImg();
    }


    /**
     * 查询兑换人数最多的前N个礼物
     * @param limit 返回记录数限制
     * @return 包含礼物标题和图片的Map列表
     */
    public Map<String, String> selectTopGifts(int limit) {
        List<Map<String, Object>> topGifts = studentActivityHistoryMapper.selectTopGifts(limit);
        Map<String, String> giftMap = new HashMap<>();
        for (Map<String, Object> gift : topGifts) {
            String title = (String) gift.get("name");
            String img = (String) gift.get("image_url");
            // 过滤掉null键，或者将null替换为默认值
            if (title != null) {
                giftMap.put(title, img != null ? img : "");
            }
        }
        return giftMap;
    }

    public List<Gift> PGift() {

        return giftMapper.PGift();
    }
}
